<template>
  <el-dialog title="资料上传" class="gl_dialog_TitleLine" :visible.sync="dialogVisible" width="660px">
    <div v-loading="dialogLoading">
      <div class="gl_mr_15 upload_box">
        <el-upload
          :action="action"
          :before-upload="beforeUpload"
          :http-request="upload"
          :auto-upload="true"
          :show-file-list="false"
          accept=".jpg,.png,.jpeg"
        >
          <i class="el-icon-plus upload" />
        </el-upload>
      </div>
      <div v-for="ktem in imgList" :key="ktem.id" class="img_box gl_mr_15 gl_mb_15 show_remove">
        <img :src="getStaticFileUrl(ktem.fileDir)">
        <i class="el-icon-delete remove" @click="remove(ktem.id)" />
      </div>
      <div v-for="(item, index) in fileList" :key="index" class="img_box gl_mr_15 gl_mb_15 show_remove">
        <img :src="getStaticFileUrl(item)">
        <i class="el-icon-delete remove" @click="beforeSaveRemove(index)" />
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="close()">取 消</el-button>
      <el-button :loading="buLoading" size="mini" type="primary" @click="submit()">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  api_GET_EventsManagementComRegisterFileCompetitionEntryFileByRegisterCompetitorRegisterId, // 查询体检资料
  api_POST_EventsManagementComRegisterFile, // 添加体检资料
  api_DELETE_EventsManagementComRegisterFileId // 删除体检资料
} from '@/extend/api/gameswaggerApi/app.js';
import {
  SiSTKWEventsManagementCreateCompetitionRegisterFileInput // 添加体检资料
} from '@/lib/form/game/swaggerForm';
import { getToken } from '@/lib/auth';
import axios from 'axios';
export default {
  name: 'UploadData',
  data() {
    return {
      dialogLoading: false,
      buLoading: false,
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`,
      SiSTKWEventsManagementCreateCompetitionRegisterFileInput: new SiSTKWEventsManagementCreateCompetitionRegisterFileInput(),
      dialogVisible: false,
      tokenInfo: getToken(),
      imgList: [],
      file: '',
      id: '',
      fileList: []
    };
  },
  methods: {
    // 打开弹窗
    open(id) {
      this.dialogVisible = true;
      this.getData(id);
      this.id = id;
      this.fileList = [];
      this.uploadDataId = id;
    },
    // 关闭弹窗
    close() {
      this.dialogVisible = false;
    },
    // 获取已上传的体检资料
    getData(id) {
      this.dialogLoading = true;
      const competitorRegisterId = id;
      api_GET_EventsManagementComRegisterFileCompetitionEntryFileByRegisterCompetitorRegisterId(competitorRegisterId).then(res => {
        this.imgList = res;
        this.dialogLoading = false;
      }).catch(() => {
        this.dialogLoading = false;
      });
    },
    // 上传图片限制
    check(file) {
      const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG或者PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    },
    beforeUpload(file) {
      const checkData = this.check(file);
      if (checkData) {
        this.file = file;
      } else {
        return false;
      }
    },
    // 上传图片
    upload() {
      return new Promise((resolve, reject) => {
        if (!this.file) reject(new Error());
        const form = new FormData();
        form.append('formFile', this.file);
        this.uploadApi(this.action, form).then(res => {
          if (res.status === 200) {
            this.fileList.push(res.data.tempUrl);
            resolve(res.data);
          } else {
            reject(res.data);
          }
        });
      });
    },
    // 上传图片的api
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, file, config);
    },
    // 上传图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 上传资料
    submit() {
      this.buLoading = true;
      this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput.competitionId = this.$route.query.id;
      this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput.competitorRegisterId = this.uploadDataId;
      this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput.fileDirs = this.fileList;
      api_POST_EventsManagementComRegisterFile(this.SiSTKWEventsManagementCreateCompetitionRegisterFileInput).then(res => {
        this.buLoading = false;
        this.dialogVisible = false;
        this.fileList = [];
        this.$message({ type: 'success', message: '上传成功' });
      }).catch(() => {
        this.buLoading = false;
        this.dialogVisible = false;
        this.fileList = [];
        this.$message({ type: 'error', message: '上传失败' });
      });
    },
    // 删除体检资料
    remove(id) {
      var that = this;
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.dialogLoading = true;
        api_DELETE_EventsManagementComRegisterFileId(id).then(res => {
          that.dialogLoading = false;
          that.$message({
            type: 'success',
            message: '删除成功!'
          });
          that.getData(this.id);
        }).catch(() => {
          that.dialogLoading = false;
          that.$message({
            type: 'error',
            message: '删除失败!'
          });
        });
      }).catch(() => {
        that.$message({
          type: 'info',
          message: '取消删除'
        });
      });
    },
    beforeSaveRemove(index) {
      this.fileList.splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>
.upload_box {
	width: 100px;
	height: 100px;
	display: inline-block;
	vertical-align: top;
}
.upload {
	width: 100px;
	height: 100px;
	cursor: pointer;
	display: inline-block;
	border-radius: 10px;
	text-align: center;
	line-height: 100px;
	border: 1px dashed #c0ccda;
}
.upload:hover {
	border: 1px dashed #409eff;
}
.img_box {
	width: 100px;
	height: 100px;
	border-radius: 10px;
	overflow: hidden;
	display: inline-block;
  position: relative;
  cursor: pointer;
}
.show_remove:hover .remove {
  display: block;
}
.remove {
  width: 100px;
	height: 100px;
  text-align: center;
  font-size: 16px;
  color: #fff;
  border-radius: 10px;
	overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(60, 60, 62,0.7);
  line-height: 100px;
  display: none;
}
img {
	width: 100%;
	height: 100%;
}
</style>
